<template>
	<!-- 总盒子 -->
	<view class="index-page">
		<view class="topbackground" style="background: linear-gradient(#B3D6FD, transparent);">
			<view class="header" :style="{ paddingTop: heightConfig.navBarPaddingTop + 'px' }">
				<view class="Narbar_bo">
					<view></view>
					<view class="title" size="19px">个人中心</view>
					<view></view>
				</view>
			</view>
			<view style="display: flex;"  @getphonenumber="getPhoneNumber">
					<!--  -->
				
				<u-button
				     v-if="!isLogin"
					:hairline="false"
					shape="circle"
					color="#428d38"
					throttleTime="2000"
					open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber"
				></u-button>
		
				<view class="avator" >
				 <image style="width: 100%; height: 100%; border-radius: 45rpx;" :src="avatorUrl">
                </image> 
				</view>
				
			
			
				<view @click="toInfoPage" style="margin-top: 45rpx; margin-left: 20rpx;">
					<view style="height: 100%; display: flex; align-items: center; font-size: 50rpx;">
						{{isLogin ? name : '未登录'}}
					</view>
					
				</view>
			</view>
			<view class="appoint">
				我的预约
			</view>

			<view class="myFun">
				<u-grid :col="3">
					<u-grid-item @click="toPage(item.path)" v-for="(item,index) in imgList">
						<image :src="item.image" mode="" style="width: 60rpx;height: 60rpx;"></image>
						<view class="grid-text">{{item.name}}</view>
					</u-grid-item>
					<!-- <u-grid-item>
                			<u-icon name="lock" :size="46"></u-icon>
                			<view class="grid-text">已预约</view>
                		</u-grid-item>
                		<u-grid-item>
                			<u-icon name="hourglass" :size="46"></u-icon>
                			<view class="grid-text">已完成</view>
                		</u-grid-item> -->
				</u-grid>
			</view>
			<view class="appoint">
				其他服务
			</view>
			<view @click="toPage(item.path)" class="service" v-for="item in serviceList">
				<view class="left">
					<image :src="item.image"></image>
				</view>
				<view class="center">
					{{item.name}}
				</view>
				<view class="right">
					<image src="/static/images2/右箭头.png"></image>
				</view>
			</view>
		</view>
         
	</view>

</template>

<script>
	import api from "@/api/homePage";
	import loginApi from "@/api/login";
	import { baseUrl } from "@/config.js"
	import { setToken } from '@/utils/auth';
	import {
		getToken
	} from "@/utils/auth";
	import {
		getQueryString
	} from "@/utils/index";

	export default {
		name: "Index",
		components: {},
		data() {
			return {
				isLogin:false,
				serviceList: [{
						image: "/static/images2/orderlist.png",
						name: "订单列表",
						path: "orderList/orderList"
					},
					{
						image: "/static/images2/clock.png",
						name: "体检指南",
						path: "phyExaGuide/phyExaGuide"
					},
					{
						image: "/static/images2/myC.png",
						name: "官方客服",
						path: "myCusService/myCusService"
					},
					{
						image: "/static/images2/privacy.png",
						name: "隐私协议",
						path: "privacyAgreement/privacyAgreement"
					},
					{
						image: "/static/images2/mymassage.png",
						name: "我的消息",
						path: "myMessage/myMessage"
					},
				],
				imgList: [{
						image: "/static/images2/wait.png",
						name: "待预约",
						path: "waitAppointment/waitAppointment"
					},
					{
						image: "/static/images2/aread.png",
						name: "已预约",
						path: "aAppointment/aAppointment"
					},
					{
						image: "/static/images2/over.png",
						name: "已完成",
						path: "Over/Over"
					},

				],
				codeUserId: null, // 上级id
				heightConfig: {},
				keyword: "",
				swiperList: [], // 轮播
				profileList: [], // 简介
				referralsList: [],
				popState: false,
				transitionShow: true,
				transitionMode: "slide-right",
				iconShow: true,
				iconMode: "slide-up",
				name:"",
				show:false,
				avatorUrl:"",
				phone:""
			};
		},
		onLoad(query) {
            
				uni.$on('avatorChange',async (data) => {
					   this.getUserinfo()
				})
			
			this.mainHeight = this.$store.getters.heightData.noTabMainHeight;
			this.heightConfig = this.$store.getters.heightData;
			this.getBannerList();
			// this.getReferralsList();

			const q = decodeURIComponent(query.q);
			let userId = getQueryString(q, "userId");
			this.codeUserId = userId || null;
			uni.setStorageSync("codeUserId", this.codeUserId);

			if (this.codeUserId) {
				let userInfo = uni.getStorageSync("userInfo");
				console.log(userInfo, 'userInfo');
				let obj = {
					promotionId: this.codeUserId,
					userId: userInfo.userId
				}
				console.log(obj, "obj");
				loginApi.binding(obj).then((res) => {
					if (res.code == 200) {

					} else {

					}
				});
			}
		},
		onShow(){
		
		    	this.getUserinfo()
			 if(uni.getStorageSync('token')){
				  this.isLogin = true
				  wx.getUserInfo({
				  success: (res) =>{
				  var userInfo = res.userInfo;
				  var nickName = userInfo.nickName;
				  var avatarUrl = userInfo.avatarUrl;
				  var gender = userInfo.gender; // 性别 0：未知、1：男、2：女
				  var province = userInfo.province;
				  var city = userInfo.city;
				  var country = userInfo.country;
			
				
				  },
				  fail:(erro)=>{
					
				  }
				  })
			 }else{
				    this.isLogin = false
			 }
		},
		
		methods: {
			toInfoPage(){
                if(!this.isLogin) return  this.$u.toast("请先登录")
				uni.navigateTo({
						url: `/subPages/userInfo/userInfo?nickName=${this.name}&avatar=${this.avatorUrl}`,
					})
			},
		   
			onChooseAvatar(e){
			
				this.avatorUrl = e.detail.avatarUrl
			},
			getUserI(){
				wx.getUserProfile({
				desc: '用于完善会员资料', // 声明获取用户个人信息后的用途
				});
				
			},
           getUserinfo(){
			   loginApi.getUserInfo().then((res)=>{
				  
					            //const filename = res.user.avatar.split("/")[-1]
 			   				this.name = res.user.nickName
			   				  //  let filename = res.user.avatar.substring(res.user.avatar.lastIndexOf("/") + 1);
						    this.avatorUrl = res.user.avatar
							this.phone = res.user.phonenumber
			   			}).catch((erro)=>{
			   				console.log(erro)
			   			})
		   },
			async getPhoneNumber(e) {
				// tologin(){
				// 	if(this.isLogin) return 
					
				// 	getPhoneNumber()
				// },
			   console.log(e,"登录")
				
				if(this.isLogin) return this.$u.toast("已登录")
				
			
				if (e.detail.errMsg != 'getPhoneNumber:ok') {
					uni.showToast({
						icon: 'none',
						title: '授权失败'
					});
					return;
				} else {
					uni.showLoading({
						title: '加载中'
					});
					const loginRes = await uni.login();
					let params = {
						code: loginRes[1].code,
						phoneCode: e.detail.code
						// encryptedData: e.detail.encryptedData,
						// iv: e.detail.iv,
						// promotionId: this.codeUserId
					};
					loginApi.weChatLogin(params).then((res) => {
						if (res.code == 200) {
							uni.hideLoading();
							setToken(res.data.token);
			               
							uni.showToast({ title: '登录成功' });
						   	this.getUserI()
			                this.isLogin = true
							
				          	// uni.authorize({
				          	//     scope: "scope.writePhotosAlbum",
				          	//     success: (res) => {
				          	//         // 用户同意授权，继续保存图片
				          	//         this.saveImageToAlbum(this.poster);
				          	//     },
				          	//     fail: () => {
				          	//         // 用户拒绝授权，提示用户开启权限
				          	//         uni.showModal({
				          	//             title: "提示",
				          	//             content: "需要您授权保存图片到相册",
				          	//             success: (result) => {
				          	//                 if (result.confirm) {
				          	//                     // 引导用户去设置页面开启权限
				          	//                     uni.openSetting();                        
				          	//                 }
				          	//             },
				          	//         });
				          	//     },
				          	// });	
							
							
							
							this.getUserinfo()
						
							uni.reLaunch({
								url: '/pages/index/index'
							});
						} else {
							uni.showToast({
								icon: 'none',
								title: '登录失败'
							});
						}
					});
				}
			},
			toPage(path) {
				
				if(!this.isLogin) return this.$u.toast("请先登录")
				
				if (path == 'myCusService/myCusService') {
					wx.makePhoneCall({
						phoneNumber: "4001-111-111"
					})
					return
				}
				uni.navigateTo({
					url: `/subPages/${path}`,
				})
			},

			// 预约
			appointMent() {
				uni.navigateTo({
					url: "/subPages/appointMent/appointMnetDataSele",
				})
			},
			// banner
			getBannerList() {
				api.getBannerList().then((res) => {
					if (res.code == 200) {
						this.swiperList = [];
						this.profileList = [];
						res.data.forEach((element) => {
							if (element.type == 1) {
								this.swiperList.push(element);
							}
							if (element.type == 2) {
								this.profileList.push(element);
							}
						});
					}
				});
			},
			// 推荐
			getReferralsList() {
				api.getReferralsList().then((res) => {
					if (res.code == 200) {
						this.referralsList = res.data;

					}
				});
			},
			swiperSkip(index, type) {
				if (type == 1) {
					// 轮播图跳转
					if (this.swiperList[index].goodId) {
						uni.navigateTo({
							url: `/subPages/details/goodDetail?id=${this.swiperList[index].goodId}`,
						});
					}
				} else if (type == 2) {
					// 主页大图跳转
					if (this.profileList[index].goodId) {
						uni.navigateTo({
							url: `/subPages/details/goodDetail?id=${this.profileList[index].goodId}`,
						});
					}
				}
			},
			searchFocus() {
				uni.navigateTo({
					url: "/subPages/details/searchPage",
				});
			},
			switchIcon() {
				this.iconShow = !this.iconShow;
			},
			pageScroll() {
				let transitionShow = this.transitionShow;
				if (transitionShow) this.transitionShow = false;
				clearTimeout(this.timer);
				this.timer = setTimeout(() => {
					this.transitionShow = true;
					clearTimeout(this.timer);
				}, 1000);
			},
			clickNavigation(item) {
				const token = getToken();
				if (!token) {
					uni.navigateTo({
						// url: "/pages/login",
					});
				} else {
					if (item.id == 1) {
						// 专属福利
					} else if (item.id == 2) {
						// 客服
					} else if (item.id == 3) {
						// 购物车
						uni.switchTab({
							url: "/pages/shopCar",
						});
					} else if (item.id == 4) {
						// 活动订阅
					}
				}
			},
		},
	};
</script>

<style lang="less" scoped>
	/deep/.u-button{
		 width: 100rpx !important;
		 height: 100rpx !important;
		 position: absolute !important;
		 margin-left: 40rpx;
		 margin-top: 29rpx;
		 border: none !important;
		 box-shadow: none !important;
		 background: none !important;
		 content: none !important;
		 transform: none !important;
         

	}
	/deep/.u-button::before{
		 background:none !important;
	}
	/deep/ .u-button:active {
	  background-color: transparent; /* 取消背景颜色变化 */
	  box-shadow: none;              /* 取消阴影 */
	  outline: none;                 /* 取消轮廓 */
	  transform: none;               /* 取消缩放或位移 */
	}
	* {
		margin: 0;
		padding: 0;
	}

	.content {
		width: 100%;
		height: 518rpx;
		background: #F7F8FA;
		padding: 34rpx;
		border-radius: 40rpx 40rpx 0rpx 0rpx;
	}

	.topbackground {
		width: 100%;
		height: 338rpx;
	
		background-size: 100% 100%;
	}

	.index-page {

		width: 750rpx;
		height: 1624rpx;
		background: #F7F8FA;
		box-sizing: border-box;
		// display: flex;
		// align-items: center;
		// flex-direction: column;
		// background-color: #fff;

		.header {
			width: 100%;
			// padding: 0 20rpx;
			// background-color: #fff;

			.logo {
				width: 200rpx;
				height: 60rpx;
				// background-color: #fee7eb;
				border-radius: 20px;
				text-align: center;
				line-height: 60rpx;
				margin: 0 auto;
			}

			.search {
				width: 670rpx;
				height: 72rpx;
				background: #FFFFFF;
				border-radius: 34rpx 34rpx 34rpx 34rpx;
				// padding: 20rpx 0;
				margin-left: 40rpx;
				margin-top: 10rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}

		.Narbar_bo {
			width: 100%;
			height: 35px;
			display: flex;
			padding: 0 28rpx;
			justify-content: space-between;
			align-items: center;

			.title {
				font-size: 18px;
				font-weight: 600;
			}
		}
	}

	.avator {
		margin: 42rpx 0 0 52rpx;
		width: 90rpx;
		height: 90rpx;
		background: #C1D0FF;
		border-radius: 98rpx 98rpx 98rpx 98rpx;
	}

	.text1 {
		margin: 42rpx 0 0 15rpx;
		width: 158rpx;
		height: 44rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #333333;
		text-align: center;
		font-style: normal;
		text-transform: none;
	}

	.text2 {
		white-space: nowrap;
		margin: 6rpx 0 0 15rpx;
		width: 164rpx;
		height: 34rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #4D4D4D;
		text-align: center;
		font-style: normal;
		text-transform: none;
	}

	.appoint {
		margin: 54rpx 0 0 34rpx;
		width: 120rpx;
		height: 42rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 30rpx;
		color: #333333;
		text-align: center;
		font-style: normal;
		text-transform: none;
	}

	.myFun {
		padding-top: 32rpx;
		margin: 28rpx 0 0 32rpx;
		width: 686rpx;
		height: 172rpx;
		background: #FFFFFF;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
	}

	.grid-text {
		font-size: 28rpx;
		margin-top: 12rpx;
		// color: $u-type-info;
	}

	.service {
		display: flex;
		margin: 24rpx 0 0 32rpx;
		width: 686rpx;
		height: 96rpx;
		background: #FFFFFF;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
	}

	.left {
		margin: 24rpx 0 0 24rpx;
		width: 48rpx;
		height: 48rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.center {
		    display: flex;
			align-items: center;
			margin-left: 20rpx;
	}

	.right {
		margin-left: 418rpx;
	
		height: 100%;
		display: flex;
        align-items: center;
		width: 40rpx;
	

		image {
			width: 40rpx;
			height: 40rpx;
		}
	}
</style>